package com.rest.common.utils;

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final String SECRET = "zclf&hcnow";

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    private static final String ISS = "iss";

    public static <T> String sign(T object, long maxAge) {
        try {
            final JWTSigner signer = new JWTSigner(SECRET);
            final Map<String, Object> claims = new HashMap<String, Object>();
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            claims.put(PAYLOAD, jsonString);
            claims.put(ISS, "hcnow");
            claims.put(EXP, System.currentTimeMillis() + maxAge);
            return signer.sign(claims);
        } catch(Exception e) {
            return null;
        }
    }


    public static<T> T unsign(String token, Class<T> classT) {
       try {
           Map<String,Object> claims = tokenExpValidate(token);
           String json = (String)claims.get(PAYLOAD);
           ObjectMapper objectMapper = new ObjectMapper();
           return objectMapper.readValue(json, classT);
       }catch (Exception e){
           e.printStackTrace();
           return null;
       }
    }

    public static boolean validateToken(String token){
        if(!StringUtils.hasLength(token)){
            return false;
        }
        return null != tokenExpValidate(token)?true :false;
    }

    public static Map<String,Object> tokenExpValidate(String token){
        final JWTVerifier verifier = new JWTVerifier(SECRET);
        try {
            Map<String,Object> claims = verifier.verify(token);
            if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
                long exp = (Long)claims.get(EXP);
                if (exp > System.currentTimeMillis()) {
                    return claims;
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    public static void main(String[] args){
//        TokenModel tokenModel = new TokenModel();
//        tokenModel.setPrefixTokenKey("child_1");
//        tokenModel.setProjectId("1");
//        String token = JWTUtils.sign(tokenModel,5*60*1000L);
//        System.out.println(token);
//    }
}